﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using WS_Manager_ShopMob.Model;

namespace WS_Manager_ShopMob.Helper
{
   
    /// <summary>
    /// Classe permettant de communiquer avec le webService
    /// </summary>
    class WebServiceHelpers
    {
    
        /// <summary>
        /// methode pour récupérer une information en GET
        /// </summary>
        /// <param name="url">url à requeter</param>
        /// <param name="methodeToExec">Méthode qui traite le resultat</param>
        public async void CallWebService(string url, ResultHandler methodeToExec)
        {
            //on instancie un webClient
            //WebClient client = new WebClient();
            HttpClient client = new HttpClient();

            //On récupère le résultat de la réponse
            HttpResponseMessage response = await client.GetAsync(url);
            if (response.StatusCode == HttpStatusCode.OK)
            {
                string result = await response.Content.ReadAsStringAsync();
                methodeToExec(result, null);
            }

        }

        /// <summary>
        /// methode pour envoyer des information au serveur
        /// </summary>
        /// <param name="url">url à requeter</param>
        /// <param name="toSend">objet à envoyer</param>
        /// <param name="serialize">Si l'objet doit êttre serialiser en JSON ou non</param>
        /// <param name="methodeToExec">Méthode qui traite le resultat</param>
        public async void CallWebService(string url, object toSend, bool serialize, ResultHandler methodeToExec)
        {
            //on traite l'objet a envoyer
            string s;
            if (serialize)
                s = JsonConvert.SerializeObject(toSend);
            else
                s = toSend.ToString();

            //on instancie un webClient
            //WebClient client = new WebClient();
            HttpClient client = new HttpClient();
            HttpContent content = new StringContent(s);
            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            HttpResponseMessage response = await client.PostAsync(url, content);
            if (response.StatusCode == HttpStatusCode.OK)
            {
                string result = await response.Content.ReadAsStringAsync();
                methodeToExec(result, null);
            }

        }
    }
}
